package com.shanks.home.util.time;

import android.os.Handler;
import android.os.Message;

/**
 * 在android自带的CountdownTimer类基础上实现定时功能
 * @author Shanks
 * @timen 2014.02.13 
 */
public abstract class AdvancedCountdownTimer {
	private static final int MSG_RUN = 1;	

	private final long mCountdownInterval;	// 定时间隔，以毫秒计
	private long mTotalTime;	// 定时时间
	private long mRemainTime;	// 剩余时间

	/**
	 * millisInFuture:定时时间，countDownInterval：定时间隔，以毫秒计
	 * @param millisInFuture
	 * @param countDownInterval
	 */
	public AdvancedCountdownTimer(long millisInFuture, long countDownInterval) {
		mTotalTime = millisInFuture;
		mCountdownInterval = countDownInterval;
		mRemainTime = millisInFuture;
	}

	/**
	 * 开始计时
	 */
	public synchronized final AdvancedCountdownTimer start() {
		if (mRemainTime <= 0) {	// 计时结束后返回
			onFinish();
			return this;
		}
		// 设置计时间隔
		mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_RUN), mCountdownInterval);
		return this;
	}
	
	/**
	 * 恢复计时
	 */
	public final void resume() {
		if (mRemainTime > 0) {
			mHandler.sendMessageAtFrontOfQueue(mHandler.obtainMessage(MSG_RUN));
		} 		
	}
	
//	/**
//	 * 恢复计时
//	 */
//	public final void resume(long millisInFuture) {
//		if (mRemainTime > 0) {
//			mHandler.sendMessageAtFrontOfQueue(mHandler.obtainMessage(MSG_RUN));
//		} else {
//			restart(millisInFuture);
//		}		
//	}
	
//	/**
//	 * 重新开始新的倒计时
//	 */
//	private final AdvancedCountdownTimer restart(long millisInFuture) {
//		mTotalTime = millisInFuture;
//		mRemainTime = millisInFuture;
//
//		start();
//
//		return this;
//	}
	
	/**
	 * 暂停计时
	 */
	public final void pause() {
		mHandler.removeMessages(MSG_RUN);
	}

	/**
	 *  取消计时
	 */
	public final void cancel() {
		mHandler.removeMessages(MSG_RUN);
	}

	public abstract void onTick(long millisUntilFinished, int percent);	// 计时中

	public abstract void onFinish();	// 计时结束

	// 通过handler更新android UI，显示定时时间
	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {

			synchronized (AdvancedCountdownTimer.this) {
				if (msg.what == MSG_RUN) {
					mRemainTime = mRemainTime - mCountdownInterval;

					if (mRemainTime <= 0) {
						onFinish();
					} else if (mRemainTime < mCountdownInterval) {
						sendMessageDelayed(obtainMessage(MSG_RUN), mRemainTime);
					} else {

						onTick(mRemainTime, new Long(100 * (mTotalTime - mRemainTime) / mTotalTime).intValue());

						sendMessageDelayed(obtainMessage(MSG_RUN),	mCountdownInterval);
					}
				} 
			}
		}
	};
}
